package com.myzhouye.biz.service;/***
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

import com.myzhouye.biz.dto.BaseFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: game01
 * @description:
 * @author: 那条蠢鱼
 * @create: 2025-11-12 09:27
 **/
@Service
@RequiredArgsConstructor
public class RedisFactoryCacheService {
    private final ReactiveRedisTemplate<String, Object> reactiveRedisTemplate;

    // Redis键格式: "user:{userId}:factories"
    private static final String USER_FACTORIES_KEY = "user:%s:factories";

    /**
     * 缓存用户工厂
     */
    public Mono<Boolean> cacheUserFactory(Long userId, BaseFactory factory) {
        String key = String.format(USER_FACTORIES_KEY, userId);
        return reactiveRedisTemplate.opsForHash()
                .put(key, factory.getId(), factory);
    }

    /**
     * 获取用户所有工厂
     */
    public Mono<List<BaseFactory>> getUserFactories(Long userId) {
        String key = String.format(USER_FACTORIES_KEY, userId);
        return reactiveRedisTemplate.opsForHash()
                .values(key)
                .cast(BaseFactory.class)
                .collectList();
    }

    /**
     * 删除用户工厂缓存
     */
    public Mono<Long> removeUserFactory(Long userId, String factoryId) {
        String key = String.format(USER_FACTORIES_KEY, userId);
        return reactiveRedisTemplate.opsForHash()
                .remove(key, factoryId);
    }

    /**
     * 更新工厂产品数量到Redis
     * @param userId 用户ID
     * @param factoryId 工厂ID
     * @param productCount 新的产品数量
     * @return Mono<Boolean> 更新结果(true=成功, false=失败)
     */
    public Mono<Boolean> updateFactoryProductCount(Long userId, String factoryId, int productCount) {
        String redisKey = String.format(USER_FACTORIES_KEY, userId);

        // 1. 从Redis获取工厂数据
        return reactiveRedisTemplate.opsForHash().get(redisKey, factoryId)
                .cast(BaseFactory.class)
                .flatMap(factory -> {
                    // 2. 更新产品数量(AtomicInteger需要显式设置新值)
                    factory.setProductNums(new AtomicInteger(productCount));

                    // 3. 保存更新后的工厂数据回Redis
                    return reactiveRedisTemplate.opsForHash()
                            .put(redisKey, factoryId, factory)
                            .thenReturn(true); // 更新成功返回true
                })
                .defaultIfEmpty(false); // 工厂不存在或获取失败返回false
    }
}
